package com.asd.system.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.asd.common.Result;
import com.asd.system.entity.Organization;
import com.asd.system.entity.Role;
import com.asd.system.entity.User;
import com.asd.system.service.IRoleService;
import com.asd.system.service.IUserService;
import com.asd.system.service.OrganizationService;
import com.asd.system.entity.vo.UserVO;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 组织的增删改查
 */
@RestController
@RequestMapping("/api/organization")
@Api(tags = "组织Api")
public class OrganizationController {
    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    /**
     * 创建组织
     */
    @ApiOperation(value = "添加组织", notes = "添加组织")

    @PostMapping("/add")
    public Result<?> addApply(@RequestBody Organization organization) {

        organizationService.save(organization);

        return Result.ok("创建成功");
    }

    /**
     * 删除组织
     */
    @ApiOperation(value = "删除组织", notes = "删除组织")
    @DeleteMapping("/remove")
    public Result<?> remove(@RequestParam("id") String id) {


        organizationService.removeOrgById(id);

        return Result.ok("删除成功");
    }


    /**
     * 设置组织管理员
     */
    @ApiOperation(value = "组织-设置组织管理员", notes = "组织-设置组织管理员")
    @PutMapping("/updateManager")
    public Result<?> updateManager(@RequestParam("orgId") String orgId, @RequestParam("userName") String userName,
                                   @RequestParam("roleId") String roleId) {

        Result<Organization> result = organizationService.updateManager(orgId, userName, roleId);
        return result;

    }

    /**
     * 修改成员状态
     */
    @ApiOperation(value = "组织-修改成员状态", notes = "组织-修改成员状态")

    @PutMapping("/updateOrgManager")
    public Result<?> addOrgManager(@RequestParam("orgId") String orgId, @RequestParam("userName") String userName,
                                   @RequestParam("roleId") String roleId) {

        Result<User> result = new Result<User>();

        //激活用户
        User user = userService.findToName(userName);
        Role role = roleService.getById(roleId);
        Organization organization = organizationService.getById(orgId);
        String admin = organization.getAdmin();
        if (user == null) {
            result.error500("未找到对应用户");
        } else if (user.getIsEnable().equals("0")) {
            user.setIsEnable("1");
        } else if (role.getName().equals("管理员")) {//判断是设置管理员

            Role role1 = roleService.getById(user.getRoleId());
            if (role1.getName().equals("管理员")) {
                result.error500("该用户是管理员，不能再次设置");
            } else {

                if (admin == null || admin.equals("")) {//管理员不存在时
                    List<String> list = new ArrayList<String>();
                    list.add(userName);
                    String str = JSON.toJSONString(list);
                    organization.setAdmin(str);
                } else {
                    List<String> list = (List<String>) JSONArray.parse(admin);
                    list.add(userName);

                    String str = JSON.toJSONString(list);
                    organization.setAdmin(str);
                }

                organizationService.updateById(organization);
                user.setOrgId(orgId);
                user.setRoleId(roleId);
                Boolean ok = userService.updateById(user);

                if (ok) {
                    result.success("设置成功");
                }
            }
        } else {//添加成员

            if (admin == null || admin.equals("")) {//管理员不存在时
                user.setOrgId(orgId);
                user.setRoleId(roleId);
                Boolean ok = userService.updateById(user);
                if (ok) {
                    result.success("修改成功!");
                }
            } else {
                List<String> list = (List<String>) JSONArray.parse(admin);

                if (list.contains(userName)) {
                    list.remove(userName);
                    String str = JSON.toJSONString(list);
                    organization.setAdmin(str);
                    organizationService.updateById(organization);

                }

                user.setOrgId(orgId);
                user.setRoleId(roleId);
                Boolean ok = userService.updateById(user);
                if (ok) {
                    result.success("修改成功!");
                }
            }


        }
        return result;

    }


    /**
     * 添加组织成员
     */
    @ApiOperation(value = "组织-添加组织成员", notes = "组织-添加组织成员")
    @PostMapping("/addOrgMembers")
    public Result<?> addOrgMembers(@RequestParam("orgId") String orgId, @RequestParam("userName") String userName,
                                   @RequestParam("roleId") String roleId) {


        Result<Organization> result = organizationService.addOrgMembers(orgId, userName, roleId);

        return result;
    }

    /**
     * 删除组织成员
     */
    @ApiOperation(value = "组织-删除组织成员", notes = "组织-删除组织成员")
    @DeleteMapping("/removeOrgMembers")
    public Result<?> removeOrgMembers(@RequestParam("id") String id, @RequestParam("userId") String userId) {

        Result<?> result = organizationService.removeOrgMembers(id, userId);

        return result;
    }

    /**
     * 删除组织管理员
     */
    @ApiOperation(value = "组织-删除组织管理员", notes = "组织-删除组织管理员")
    @DeleteMapping("/removeOrgAdmin")
    public Result<?> removeOrgAdmin(@RequestParam("id") String id, @RequestParam("userName") String userName) {

        Result<?> result = organizationService.removeOrgAdmin(id, userName);

        return result;
    }


    /**
     * 查询组织成员信息
     */
    @ApiOperation(value = "组织-查询组织成员信息", notes = "组织-查询组织成员信息")
    @GetMapping("/queryOrgMembersInfo")
    public Result<?> queryOrgMembersInfo(@RequestParam("orgId") String orgId,
                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                         @RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize) {
        List<UserVO> userVOList = userService.getByOrgId(orgId);

        if (userVOList.size() > 0) {

        Page page = new Page();
        int size = userVOList.size();
        if (pageSize > size) {
            pageSize = size;
        }
        //求出最大页数，防止pageNo越界
        int maxPage = size % pageSize == 0 ? size / pageSize : size / pageSize + 1;
        if (pageNo > maxPage) {
            pageNo = maxPage;
        }
        //当前页第一条数据下标
        int curIds = pageNo > 1 ? (pageNo - 1) * pageSize : 0;

        List pageList = new ArrayList<>();

        //将当前页的数据放进pageList
        for (int i = 0; i < pageSize && curIds + i < size; i++) {
            pageList.add(userVOList.get(curIds + i));
        }
        page.setCurrent(pageNo).setSize(pageSize).setTotal(userVOList.size()).setRecords(pageList);

        return Result.ok(page);
        }else {
            return Result.ok("本组织暂无成员~~");
        }

    }


    /**
     * 修改组织基本信息
     */
    @ApiOperation(value = "组织-修改组织基本信息", notes = "组织-修改组织基本信息")
    @PutMapping("/updateOrgBasicInfo")
    public Result<?> updateOrgBasicInfo(@RequestParam(value = "id",required = true) String id,
                                        @RequestParam(value = "name",required = false) String name,
                                        @RequestParam(value = "note",required = false) String note) {
        Result<Organization> result = new Result<Organization>();

        Organization oldOrg = organizationService.getById(id);
        if (oldOrg == null) {
            result.error500("未找到对应组织");
        } else {

            if (StringUtils.isNotEmpty(name)){
                oldOrg.setName(name);
            }
            if (StringUtils.isNotEmpty(note)){
                oldOrg.setNote(note);
            }

            organizationService.updateById(oldOrg);
            result.success("修改成功");

        }
        return result;
    }


    /**
     * 修改组织
     */
    @ApiOperation(value = "修改组织", notes = "修改组织")
    @PutMapping("/update")
    public Result<?> update(@RequestBody Organization organization) {
        Result<Organization> result = new Result<Organization>();

        Organization oldOrg = organizationService.getById(organization.getId());
        if (oldOrg == null) {
            result.error500("未找到对应组织");
        } else {

//            if (!(organization.getName() == null || organization.getName().equals(""))) {
//                oldOrg.setName(organization.getName());
//            }
            if (!(organization.getAdmin() == null || organization.getAdmin().equals(""))) {

                User user = userService.findToName(organization.getAdmin());
                if (user == null) {
                    return result.error500("输入用户不存在!");
                } else {
                    user.setOrgId(organization.getId());
                    userService.updateById(user);
//                    oldOrg.setAdmin(organization.getAdmin());
                }
            }
//            if (!(organization.getAvatar() == null || organization.getAvatar().equals(""))) {
//                oldOrg.setAvatar(organization.getAvatar());
//            }
//            if (!(organization.getNote() == null || organization.getNote().equals(""))) {
//                oldOrg.setNote(organization.getNote());
//            }
//            oldOrg.setName(organization.getName());
//            oldOrg.setAvatar(organization.getAvatar());
//            oldOrg.setNote(organization.getNote());

            boolean ok = organizationService.updateById(organization);
//            boolean ok = organizationService.updateById(oldOrg);

            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 查询组织
     */
    @ApiOperation(value = "查询组织", notes = "查询组织")
    @GetMapping("/query")
    public Result<?> query(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize) {

        List<Organization> list = organizationService.list();

        if (list.size() > 0) {
            Page page = new Page();
            int size = list.size();
            if (pageSize > size) {
                pageSize = size;
            }
            //求出最大页数，防止pageNo越界
            int maxPage = size % pageSize == 0 ? size / pageSize : size / pageSize + 1;
            if (pageNo > maxPage) {
                pageNo = maxPage;
            }
            //当前页第一条数据下标
            int curIds = pageNo > 1 ? (pageNo - 1) * pageSize : 0;

            List pageList = new ArrayList<>();

            //将当前页的数据放进pageList
            for (int i = 0; i < pageSize && curIds + i < size; i++) {
                pageList.add(list.get(curIds + i));
            }
            page.setCurrent(pageNo).setSize(pageSize).setTotal(list.size()).setRecords(pageList);

            return Result.ok(page);
        }else {
            return Result.ok("暂无组织,请添加！");
        }
    }
}
